﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BA2009.DataAccess.Context;
using BA2009.DataAccess.Entities;
using System.Data.Linq;
using BA2009.Data.Filters;
namespace BA2009.Data.DataAccess
{
    public class BannerRepository : RepositoryBase<BA2009.Entities.Banner>, IBannerRepository
    {

        private MapTablesRepository bannerResourceRepository = new MapTablesRepository("BannerID", "ResourceID", "BannerResource");
        private MapTablesRepository bannerPositionRepository = new MapTablesRepository("BannerID", "BannerPositionID", "BannerPositionMap");

        /// <summary>
        /// Find all banners from list of banners
        /// </summary>
        /// <returns></returns>
        public override IQueryable<BA2009.Entities.Banner> FindAll()
        {
            var listBanner = from b in db.Banners
                             select new BA2009.Entities.Banner
                             {
                                 BannerID = b.BannerID,
                                 BannerName = b.BannerName,
                                 BannerTypeID=b.BannerTypeID,
                                 Code = b.Code
                             };

            return listBanner;

        }

        /// <summary>
        /// Return banner from list of banners by bannerid.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override BA2009.Entities.Banner GetById(int id)
        {
          
            var banner = this.FindAll().WithID(id).SingleOrDefault();

            var resources = (from r in db.BannerResources
                            where r.BannerID == id
                            select r).ToList();

            IList<int> res = new List<int>();
            if (resources != null && resources.Count > 0)
            {
                foreach (var r in resources)
                {
                    res.Add(r.ResourceID);
                }
            }

            //Banner's resources
            banner.Resources = res;

            var positions = (from p in db.BannerPositionMaps
                             where p.BannerID == id
                             select p).ToList();

            IList<int> pos = new List<int>();
            if (positions != null && positions.Count > 0)
            {
                foreach (var p in positions)
                {
                    pos.Add(p.BannerPositionID);
                }
            }

            banner.BannerPositions = pos;


            return banner;

        }

        

        protected override void Save(object linqEnity, BA2009Context dbContext, params object[] maps)
        {

            var banner = linqEnity as Banner;

            dbContext.Banners.InsertOnSubmit(banner);
            dbContext.SubmitChanges();

            if (maps.Length != 2)
            {
                throw new InvalidOperationException("Tham số truyền vào hàm Save của BannerRepository sai.");
            }

            // Insert map tables
            IList<Entities.MapEntity> resources = maps[0] as IList<Entities.MapEntity>;
            if (resources != null)
            {
              
                foreach (var resource in resources)
                {
                    resource.ID1 = banner.BannerID;
                }

                bannerResourceRepository.Insert(resources, dbContext);
            }

            IList<Entities.MapEntity> bannerPositionMaps = maps[1] as IList<Entities.MapEntity>;
            if (bannerPositionMaps != null)
            {
                foreach (var position in bannerPositionMaps)
                {
                    position.ID1 = banner.BannerID;
                }
                bannerPositionRepository.Insert(bannerPositionMaps, dbContext);

            }
          
             
              
            dbContext.SubmitChanges();


        }

        protected override void Delete(int id, BA2009Context dbContext)
        {
            // Delete all map table
            var positionMap = (from pm in dbContext.BannerPositionMaps
                               where pm.BannerID == id
                               select pm).AsEnumerable();

            dbContext.BannerPositionMaps.DeleteAllOnSubmit<BannerPositionMap>(positionMap);

            var resourceMap = (from rm in dbContext.BannerResources
                               where rm.BannerID == id
                               select rm).AsEnumerable();
            dbContext.BannerResources.DeleteAllOnSubmit<BannerResource>(resourceMap);

            dbContext.SubmitChanges();
            var banner = (from b in dbContext.Banners
                          where b.BannerID == id
                          select b).SingleOrDefault();
            dbContext.Banners.DeleteOnSubmit(banner);
            dbContext.SubmitChanges();

        }

        protected override void Update(object itemToUpdate, object orginialItem, BA2009Context dbContext, params object[] maps)
        {
            if (maps.Length != 2)
            {
                throw new InvalidOperationException("Tham số truyền vào hàm Update của BannerRepository sai.");
            }
          
            var entity = itemToUpdate as Banner;
            var original = orginialItem as Banner;
            dbContext.Banners.Attach(entity, original);
            dbContext.SubmitChanges();
            // Update map tables
            IList<Entities.MapEntity> resources = maps[0] as IList<Entities.MapEntity>;
            if (resources != null)
            {
                bannerResourceRepository.Update(resources, dbContext);
            }

            IList<Entities.MapEntity> bannerPositionMaps = maps[1] as IList<Entities.MapEntity>;

            if (bannerPositionMaps != null)
                bannerPositionRepository.Update(bannerPositionMaps, dbContext);

            dbContext.SubmitChanges();
          
        }

        protected override object GetLinqEntity(int id)
        {
            var data= (from b in db.Banners
                   where b.BannerID == id
                   select b).SingleOrDefault();

            db.Refresh(RefreshMode.OverwriteCurrentValues, data);

            return data;
        }

      

        public void Ahah()
        {
            throw new NotImplementedException();
        }

      
    }
}
